package com.sbl.bajw.pc.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sbl.bajw.common.DbManager;
import com.sbl.bajw.common.MyBatisDao;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.mapper.CameraHouseModelDao;
import com.sbl.bajw.pc.model.AttFileModel;
import com.sbl.bajw.pc.model.CameraHouseModel;
import com.sbl.bajw.pc.model.CameraHouseSelectModel;
import com.sbl.bajw.util.LogUtil;

@Service
public class CameraHouseService {

	@Resource
	private CameraHouseModelDao dao;
	
	@Resource
	private MyBatisDao gridDao;
	
	@Resource
	private AttFileService attfileService;
	
	static Logger log;
	
	static {
		log = LogUtil.getLogger("CameraHouse");
	}
	
	@Transactional(readOnly = false)
	public String insert(CameraHouseModel model) throws Exception{
		try {
			log.info(model.getCreater() + "开始："+model.toString()+",经度："+RequestUnit.getString("lon"));
			checkModel(model);
			
			if(model.getUuid() != null && dao.getByUUID(model.getUuid()) > 0){
				throw new MessageException("重复提交", "3");
			}
			uploadFile(model);
			dao.insert(model);
			log.info(model.getCreater() + "属性入库成功");
		} catch (Exception e) {
			log.info(model.getCreater() + "上传失败：" + e.getMessage());
			e.printStackTrace();
			throw e;
		}
		return model.getId();
	}
	
	@Transactional(readOnly = false)
	public void updateApp(CameraHouseModel model) throws Exception{
		try {
			log.info(model.getCreater() + "开始修改"+model.toString());
			String userid = RequestUnit.getString("user_id");
			model.setUpdater(userid);
			model.setCreater(userid);
			uploadFileU(model);
			model.setIsQuelity("0");
			dao.update(model);
			log.info(model.getCreater() + "属性修改成功");
		} catch (Exception e) {
			log.info(model.toString() + ",修改异常：" + e.getMessage());
			e.printStackTrace();
			throw e;
		}
	}
	
	@Transactional(readOnly = false)
	public void update(CameraHouseModel model) throws MessageException{
		try {
			log.info("开始修改："+model.toString());
			model.setUpdater(SessionUnit.getUserId());
			dao.update(model);
		} catch (Exception e) {
			log.info(model.getCreater() + "修改异常：" + e.getMessage());
			e.printStackTrace();
			throw new MessageException("修改失败", "3");
		}
	}
	
	public List<HashMap<String, String>> getPics(String id){
		List<HashMap<String, String>> pics = dao.getPics(id);
		return pics;
	}
	
	public List<CameraHouseModel> getModelsByIds(){
		String idsStr = RequestUnit.getString("ids");
		String[] ids = idsStr.split(",");
		if(ids.length < 1){
			return null;
		}
		List<CameraHouseModel> models = dao.getModelsByIds(ids);
		return models;
	}
	
	public String getList(HashMap<String, Object> parm){
		String result = gridDao.selectPage(CameraHouseModelDao.class, parm, "getList");
		return result;
	}
	
	public List<HashMap<String, String>> getListApp(HashMap<String, Object> parm){
		List<HashMap<String, String>> list = dao.getListApp(parm);
		return list;
	}
	
	public int getCountApp(HashMap<String, Object> parm){
		int num = dao.getCountApp(parm);
		return num;
	}
	
	public List<CameraHouseSelectModel> getHouseListForCamera(String userid){
		List<CameraHouseSelectModel> list = dao.getHouseListForCamera(userid);
		return list;
	}
	
	public List<CameraHouseModel> downloadCameraHouseList(HashMap<String, Object> parm){
		List<CameraHouseModel> list = dao.getList(parm);
		return list;
	}
	
	public CameraHouseModel getModel(String id){
		CameraHouseModel model = dao.getModel(id);
		return model;
	}
	
	public String uploadFile(CameraHouseModel model) throws Exception {
		String id = dao.getCameraHouseId();

		if (id == null || id.equals("")) {
			throw new MessageException("ID不能为空", "2");
		}

		String resultPath = "";
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssS");
		
		FileItem item = null;
		int i = 1;
		while((item = RequestUnit.getFileItem("img" + i)) != null){
			String dataStr = sf.format(Calendar.getInstance().getTime());
			
			AttFileModel filemodel = new AttFileModel();
			filemodel.setBusinessType("6");
			filemodel.setFileDir("camera");
			filemodel.setFileName(dataStr + i +"_img_house_" + id);
			filemodel.setGroupid(id);
			filemodel.setItem(item);
			filemodel.setUserid(model.getCreater());
			filemodel.setFiletype("img");
			attfileService.insert(filemodel);
			log.info(model.getCreater() + "图片上传成功：" + resultPath);
			i++;
		}
		
		model.setId(id);
		
		return resultPath;
	}
	
	public String uploadFileU(CameraHouseModel model) throws Exception {

		String resultPath = "";
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssS");
		
		FileItem item = null;
		int i = 1;
		while((item = RequestUnit.getFileItem("img" + i)) != null){
			String dataStr = sf.format(Calendar.getInstance().getTime());
			
			AttFileModel filemodel = new AttFileModel();
			filemodel.setBusinessType("6");
			filemodel.setFileDir("camera");
			filemodel.setFileName(dataStr + i +"_img_house_" + model.getId());
			filemodel.setGroupid(model.getId());
			filemodel.setItem(item);
			filemodel.setUserid(model.getCreater());
			filemodel.setFiletype("img");
			attfileService.insert(filemodel);
			log.info(model.getCreater() + "图片上传成功：" + resultPath);
			i++;
		}
		
		return resultPath;
	}
	
	public String getCameraHouseCode(String policeStationId) throws Exception{
		DbManager.getConn().setAutoCommit(false);
		String lockSql = "UPDATE CAMERA_HOUSE_CODE SET CURRENT_ID = CURRENT_ID+1,UPDATETIME = SYSDATE WHERE POLICE_STATION_ID = ?";
		
		List<String> parm = new ArrayList<String>();
		parm.add(policeStationId);
		DbManager.executeUpdate(lockSql, parm);
		
		String getValSql = " SELECT PREFIX || CURRENT_ID FROM CAMERA_HOUSE_CODE WHERE POLICE_STATION_ID = ? ";
		String value = DbManager.executeScalar(getValSql, parm) + "";
		DbManager.getConn().setAutoCommit(true);
		DbManager.getConn().commit();
		return value;
	}
	
	public HashMap<String, Object> getStatisticOnDay(){
		HashMap<String, Object> map = dao.getStatisticOnDay();
		return map;
	}
	
	public void checkModel(CameraHouseModel model) throws MessageException{
		if(model.getAddress() == null || model.getAddress().equals("")){
			throw new MessageException("地址不能为空");
		}
		
		if(model.getPoliceStation() == null || model.getPoliceStation().equals("")){
			throw new MessageException("所属派出所不能为空");
		}
		
		if( model.getLon() < 100){
			throw new MessageException("经纬度不合法", "3");
		}
		
		if(dao.checkNameExists(model.getName()) > 0){
			throw new MessageException("存在同名的监控室，请修改名称");
		}
	}
	
	public List<HashMap<String, String>> getCenterCount(HashMap<String, String> parm){
		List<HashMap<String, String>> result = dao.getCenterCount(parm);
		return result;
	}
	
	public List<HashMap<String, String>> getModelsForMap(HashMap<String, String> parm){
		List<HashMap<String, String>> result = dao.getModelsForMap(parm);
		return result;
	}
}
